import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { projectService } from '@/services/project.service';
import type { Project, CreateProjectDto, UpdateProjectDto, ProjectListParams } from '@/types/project';
import { message } from 'antd';

interface ProjectState {
  // 状态
  projects: Project[];
  currentProject: Project | null;
  isLoading: boolean;
  error: string | null;
  total: number;

  // Actions
  fetchProjects: (params?: ProjectListParams) => Promise<void>;
  fetchProject: (id: string) => Promise<void>;
  createProject: (data: CreateProjectDto) => Promise<Project | null>;
  updateProject: (id: string, data: UpdateProjectDto) => Promise<void>;
  deleteProject: (id: string) => Promise<void>;
  reorderProjects: (projectIds: string[]) => Promise<void>;
  duplicateProject: (id: string, newName?: string) => Promise<void>;
  setCurrentProject: (project: Project | null) => void;
  clearError: () => void;
}

export const useProjectStore = create<ProjectState>()(
  devtools(
    persist(
      (set, get) => ({
        // 初始状态
        projects: [],
        currentProject: null,
        isLoading: false,
        error: null,
        total: 0,

        // 获取项目列表
        fetchProjects: async (params?: ProjectListParams) => {
          set({ isLoading: true, error: null });
          try {
            const response = await projectService.getProjects(params);
            set({
              projects: response.projects,
              total: response.total,
              isLoading: false,
            });
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '获取项目列表失败';
            set({ error: errorMessage, isLoading: false });
            message.error(errorMessage);
          }
        },

        // 获取单个项目
        fetchProject: async (id: string) => {
          set({ isLoading: true, error: null });
          try {
            const project = await projectService.getProject(id);
            set({
              currentProject: project,
              isLoading: false,
            });
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '获取项目详情失败';
            set({ error: errorMessage, isLoading: false });
            message.error(errorMessage);
          }
        },

        // 创建项目
        createProject: async (data: CreateProjectDto) => {
          set({ isLoading: true, error: null });
          try {
            const project = await projectService.createProject(data);
            set((state) => ({
              projects: [project, ...state.projects],
              total: state.total + 1,
              isLoading: false,
            }));
            message.success('项目创建成功');
            return project;
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '创建项目失败';
            set({ error: errorMessage, isLoading: false });
            message.error(errorMessage);
            return null;
          }
        },

        // 更新项目
        updateProject: async (id: string, data: UpdateProjectDto) => {
          set({ isLoading: true, error: null });
          try {
            const updatedProject = await projectService.updateProject(id, data);
            set((state) => ({
              projects: state.projects.map((p) => (p.id === id ? updatedProject : p)),
              currentProject: state.currentProject?.id === id ? updatedProject : state.currentProject,
              isLoading: false,
            }));
            message.success('项目更新成功');
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '更新项目失败';
            set({ error: errorMessage, isLoading: false });
            message.error(errorMessage);
          }
        },

        // 删除项目
        deleteProject: async (id: string) => {
          set({ isLoading: true, error: null });
          try {
            await projectService.deleteProject(id);
            set((state) => ({
              projects: state.projects.filter((p) => p.id !== id),
              total: state.total - 1,
              currentProject: state.currentProject?.id === id ? null : state.currentProject,
              isLoading: false,
            }));
            message.success('项目删除成功');
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '删除项目失败';
            set({ error: errorMessage, isLoading: false });
            message.error(errorMessage);
          }
        },

        // 重新排序项目
        reorderProjects: async (projectIds: string[]) => {
          const previousProjects = get().projects;

          // 乐观更新
          const reorderedProjects = projectIds
            .map((id) => previousProjects.find((p) => p.id === id))
            .filter(Boolean) as Project[];

          set({ projects: reorderedProjects });

          try {
            await projectService.updateProjectsOrder(projectIds);
            message.success('排序已保存');
          } catch (error) {
            // 回滚
            set({ projects: previousProjects });
            const errorMessage = error instanceof Error ? error.message : '保存排序失败';
            message.error(errorMessage);
          }
        },

        // 复制项目
        duplicateProject: async (id: string, newName?: string) => {
          set({ isLoading: true, error: null });
          try {
            const project = await projectService.duplicateProject(id, newName);
            set((state) => ({
              projects: [project, ...state.projects],
              total: state.total + 1,
              isLoading: false,
            }));
            message.success('项目复制成功');
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '复制项目失败';
            set({ error: errorMessage, isLoading: false });
            message.error(errorMessage);
          }
        },

        // 设置当前项目
        setCurrentProject: (project: Project | null) => {
          set({ currentProject: project });
        },

        // 清除错误
        clearError: () => {
          set({ error: null });
        },
      }),
      {
        name: 'project-storage',
        partialize: (state) => ({
          currentProject: state.currentProject,
        }),
      }
    ),
    {
      name: 'ProjectStore',
    }
  )
);
